import { shallowReactive, reactive, watch, toRef } from 'vue';
import { menuController } from '@ionic/core';
import { IPSDEFormGroupPanel, IPSDEFormItem, IPSDEFormPage } from '@ibiz/dynamic-model-api';
import { IMobSearchFormCtrlController, LogUtil, MobSearchFormCtrlController, Util } from 'ibz-core';
import { AppMobSearchFormProps } from 'ibz-core';
import { GenerateComponent } from '../component-base';
import { AppMobForm } from './app-mob-form/app-mob-form';

/**
 * 移动端搜索表单
 *
 * @author chitanda
 * @date 2021-08-06 10:08:39
 * @export
 * @class AppMobSearchForm
 * @extends {ComponentBase}
 */
export class AppMobSearchForm extends AppMobForm<AppMobSearchFormProps> {
  /**
   * @description 搜索表单控制器
   * @protected
   * @type {IMobSearchFormCtrlController}
   * @memberof AppMobSearchForm
   */
  protected c!: IMobSearchFormCtrlController;

  /**
   * @description 搜索表单uuid
   * @type {string}
   * @memberof AppMobSearchForm
   */
  public uuid: string = Util.createUUID();

  /**
   * @description 设置响应式
   * @memberof AppMobSearchForm
   */
  setup() {
    this.c = shallowReactive<MobSearchFormCtrlController>(
      this.getCtrlControllerByType('SEARCHFORM') as MobSearchFormCtrlController,
    );
    watch(
      () => this.c.isExpandSearchForm,
      () => {
        if (this.c.isExpandSearchForm) {
          this.openSearchForm();
        }
      },
      {
        immediate: true,
      },
    );
    // TODO 不能使用super.setup 这会导致c指向问题
    this.controlIsLoaded = toRef(this.c, 'controlIsLoaded');
    this.initReactive();
    this.emitCtrlEvent = this.emitCtrlEvent.bind(this);
    this.c.hooks.event.tap(this.emitCtrlEvent);
    this.emitCloseView = this.emitCloseView.bind(this);
    this.c.hooks.closeView.tap(this.emitCloseView);
  }

  /**
   * @description 初始化响应数据
   * @memberof AppMobSearchForm
   */
  public initReactive() {
    super.initReactive();
    this.c.isExpandSearchForm = reactive(this.c.isExpandSearchForm);
  }

  /**
   * @description 重置
   * @memberof AppMobSearchForm
   */
  public onReset() {
    this.c.onReset();
  }

  /**
   * @description 搜索
   * @memberof AppMobSearchForm
   */
  public onSearch() {
    this.c.onSearch();
    this.closeSearchForm();
  }

  /**
   * @description 打开搜索表单
   * @memberof AppMobSearchForm
   */
  public async openSearchForm() {
    await menuController.enable(true, this.uuid);
    menuController.open(this.uuid);
  }

  /**
   * @description 关闭搜索表单
   * @memberof AppMobSearchForm
   */
  public closeSearchForm() {
    menuController.close(this.uuid);
  }

  /**
   * @description 根据成员类型绘制
   * @param {*} modelJson 模型数据
   * @param {number} index 索引
   * @return {*}
   * @memberof AppMobSearchForm
   */
  public renderByDetailType(modelJson: any, index: number) {
    if (modelJson.getPSSysPFPlugin()?.pluginCode) {
      const ctrlItemPluginInstance = App.getPluginService().getCtrlItemPluginByTag(
        modelJson.getPSSysPFPlugin()?.pluginCode || '',
      );
      if (ctrlItemPluginInstance) {
        return ctrlItemPluginInstance.renderItem(this.c.data[modelJson.name], this.c, this);
      }
    } else {
      switch (modelJson.detailType) {
        case 'FORMPAGE':
          return this.renderFormPage(modelJson as IPSDEFormPage, index);
        case 'GROUPPANEL':
          return this.renderGroupPanel(modelJson as IPSDEFormGroupPanel, index);
        case 'FORMITEM':
          return this.renderFormItem(modelJson as IPSDEFormItem, index);
        default:
          LogUtil.log(
            `${this.$tl('share.notsupported', '暂未实现')} ${modelJson.detailType} ${this.$tl(
              'widget.mobsearchform.detailtype',
              '类型表单成员',
            )}`,
          );
      }
    }
  }

  /**
   * @description 绘制搜索表单
   * @param {*} className 类名
   * @param {*} controlStyle 样式
   * @return {*}
   * @memberof AppMobSearchForm
   */
  renderSearchForm(className: any, controlStyle: any) {
    return [
      <ion-header class={'searchForm-header'}>
        <ion-toolbar>
          <ion-buttons slot='end'>
            <ion-button onClick={() => this.openSearchForm()} id='searchForm'>
              {this.$tl('widget.mobsearchform.filter', '过滤')}
            </ion-button>
          </ion-buttons>
        </ion-toolbar>
      </ion-header>,
      <ion-menu side='end' menuId={this.uuid} contentId='searchForm'>
        <ion-content>
          <div class={className} style={controlStyle}>
            {this.renderFormContent()}
          </div>
        </ion-content>
        <ion-footer class={'searchForm-footer'}>
          <ion-toolbar>
            <ion-button size='small' onClick={() => this.onSearch()}>
              {this.$tl('widget.mobsearchform.search', '搜索')}
            </ion-button>
            <ion-button size='small' onClick={() => this.onReset()}>
              {this.$tl('widget.mobsearchform.reset', '重置')}
            </ion-button>
          </ion-toolbar>
        </ion-footer>
      </ion-menu>,
    ];
  }

  /**
   * @description 绘制快速搜索表单
   * @param {*} className 类名
   * @param {*} controlStyle 样式
   * @memberof AppMobSearchForm
   */
  renderQuickSearchForm(className: any, controlStyle: any) {
    return (
      <ion-header>
        <div class={className} style={controlStyle}>
          {this.renderFormContent()}
        </div>
      </ion-header>
    );
  }

  /**
   * @description 绘制搜索表单内容
   * @return {*}
   * @memberof AppMobSearchForm
   */
  renderSearchFormContent() {
    const controlStyle = {
      width: this.c.controlInstance.width
        ? `${this.c.controlInstance.width}px`
        : this.c.controlInstance.formWidth
        ? `${this.c.controlInstance.formWidth}`
        : '',
      height: this.c.controlInstance.height ? `${this.c.controlInstance.height}px` : '',
    };
    const className = { ...this.classNames };
    if (Object.is(this.c.controlInstance.name, 'quicksearchform') || this.c.expandSearchForm) {
      return this.renderQuickSearchForm(className, controlStyle);
    } else {
      return this.renderSearchForm(className, controlStyle);
    }
  }

  /**
   * @description 绘制
   * @return {*}
   * @memberof AppMobSearchForm
   */
  render() {
    if (!this.controlIsLoaded.value) {
      return null;
    }
    return this.renderSearchFormContent();
  }
}

// 搜索表单部件
export const AppMobSearchFormComponent = GenerateComponent(AppMobSearchForm, Object.keys(new AppMobSearchFormProps()));
